package com.qth.valet.controller;

import com.qth.valet.common.annotation.Logs;
import com.qth.valet.common.annotation.Release;
import com.qth.valet.common.annotation.RepeatSubmit;
import com.qth.valet.common.exception.PaymentException;
import com.qth.valet.common.theadlocal.UserOrDriverIdHolder;
import com.qth.valet.common.utils.ResponseResult;
import com.qth.valet.common.utils.StatusConstants;
import com.qth.valet.entity.po.*;
import com.qth.valet.entity.req.PayReq;
import com.qth.valet.entity.vo.WxPayment;
import com.qth.valet.entity.vo.WxPaymentResponse;
import com.qth.valet.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @author 蔡徐坤
 * @since 2025-08-26
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/qth/payment")
public class PaymentController {

    private final OrdersService ordersService;

    private final CouponUserService couponUserService;

    private final CouponService couponService;

    private final WechatPaymentService wechatPaymentService;

    private final UsersService usersService;

    /**
     * 用户支付
     */
    @Logs(operation = "微信支付")
    @PostMapping("/pay")
    @RepeatSubmit
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<WxPaymentResponse> pay(@RequestBody PayReq payReq) {
        // 查询订单信息
        Orders dbOrder = ordersService.getById(payReq.getOrderId());
        if (dbOrder == null || dbOrder.getStatus() != StatusConstants.ORDER_PENDING_PAY) {
            throw new PaymentException();
        }
        // 优惠券信息
        Coupon coupon = null;
        if (payReq.getCouponUserId() != null) {
            // 用户的优惠券
            CouponUser couponUser = couponUserService.getById(payReq.getCouponUserId());
            // 校验
            if (couponUser == null || couponUser.getIsUsed()) {
                throw new PaymentException();
            }
            // 优惠券信息
            coupon = couponService.getById(couponUser.getCouponId());
            // 校验
            if (coupon == null || dbOrder.getPrice() < coupon.getAtLeast()) {
                throw new PaymentException();
            } else if (coupon.getExpireDate().before(new Date())) {
                throw new RuntimeException("优惠券已过期");
            }
        }
        WxPayment wxPayment = new WxPayment();
        wxPayment.setOrderId(payReq.getOrderId());
        // 查询openId
        Users user = usersService.getById(UserOrDriverIdHolder.getUserId());
        wxPayment.setOpenid(user.getOpenId());
        wxPayment.setDescription("代驾司机费用");
//        wxPayment.setAmount(this.getPrice(dbOrder.getPrice(), coupon));
        wxPayment.setAmount(new BigDecimal("0.01"));

        return wechatPaymentService.createPayment(wxPayment, payReq, coupon);
    }

    @PostMapping("/notify")
    @Logs(operation = "支付回调")
    @Release
    public String paymentNotify(HttpServletRequest request) {
        return wechatPaymentService.handlePaymentNotify(request);
    }

    @GetMapping("/queryPayment")
    public ResponseResult<Object> queryPayment(String orderId){
        return wechatPaymentService.queryPayment(orderId);
    }

    @GetMapping("/closePayment")
    public ResponseResult<Object> closePayment(String orderId){
        return wechatPaymentService.closePayment(orderId);
    }

    private BigDecimal getPrice(Long price, Coupon coupon){
        BigDecimal payPrice = new BigDecimal(Long.toString(price / 100));
        BigDecimal result;
        if (coupon != null) {
            // 有优惠券
            result = payPrice.subtract(new BigDecimal(coupon.getAmount() / 100));
        }else{
            result = payPrice;
        }
        if (result.signum() < 0) {
            result = new BigDecimal(0);
        }
        return result;
    }
}
